package com.lft.examsys.service;

import com.lft.examsys.entity.CreditUser;
import com.lft.examsys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserLogin implements UserDetailsService {
    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private HttpServletRequest req;



    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        User user = userService.findByName(username);
        if (user == null) {
            req.setAttribute("errMsg","账号或密码错误，请重新输入");
        }

        if (user.isBanned()) {
            req.setAttribute("errMsg","用户已被封禁，请联系管理员");
        }

        String password = req.getParameter("password");
        if (!encoder.matches(password, user.getPassword())) {
            req.setAttribute("errMsg","账号或密码错误，请重新输入");
        }

        List<String> permissions = null;
        if (user.getUsername().equalsIgnoreCase("root")) {
            permissions = permissionService.getAllPermissionName();

        } else {
            if (user.getRoleId() == null) {
                permissions = permissionService.getActivePermissionIdByRoleId("default");
            } else {
                permissions = permissionService.getActivePermissionIdByRoleId(user.getRoleId());
            }
        }
        user.fillAuthorize(permissions);
        return new CreditUser(user);
    }
}
